package com.wayoos.wap.server.watchdog;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.ServerSocket;
import java.net.Socket;

public class WatchDogHTTPServer {

	private ServerSocket serverSocket;

	private Thread acceptThread;

	private byte[] content;
	private byte[] header;
	private int port = 80;

	private WatchDogEventHandler watchDogEventHandler;

	public WatchDogHTTPServer(WatchDogEventHandler eventHandler, String MIMEType, int port)
			throws UnsupportedEncodingException {
		this.watchDogEventHandler = eventHandler;
		this.content = "TEST".getBytes("UTF8");
		this.port = port;
		String header = "HTTP/1.0 200 OK\r\n" + "Server: WapServer 1.0\r\n" + "Content-length: "
				+ this.content.length + "\r\n" + "Content-type: " + MIMEType + "\r\n\r\n";
		this.header = header.getBytes("ASCII");

	}

	public void start() throws IOException {
		serverSocket = new ServerSocket(port);

		acceptThread = new Thread(new Runnable() {

			@Override
			public void run() {
				processConnection();
			}
		});
		acceptThread.start();

		System.out.println("Accepting connections on port " + serverSocket.getLocalPort());
		System.out.println("Data to be sent:");
		System.out.write(this.content);
	}

	public void stop() {
		acceptThread = null;
		try {
			serverSocket.close();
		} catch (IOException e) {
		}
	}

	private void processConnection() {
		while (acceptThread == Thread.currentThread()) {
			try {
				Socket connection = serverSocket.accept();

				processRequest(connection);

				if (connection != null)
					connection.close();
			} catch (IOException e) {
			}
		}
	}

	private void processRequest(Socket connection) {

		try {
			OutputStream out = new BufferedOutputStream(connection.getOutputStream());
			InputStream in = new BufferedInputStream(connection.getInputStream());
			// read the first line only; that's all we need
			StringBuffer request = new StringBuffer(80);
			while (true) {
				int c = in.read();
				if (c == '\r' || c == '\n' || c == -1)
					break;
				request.append((char) c);

			}

			System.out.println(request);

			watchDogEventHandler.onEvent(new WatchDogEvent());

			// If this is HTTP/1.0 or later send a MIME header
			if (request.toString().indexOf("HTTP/") != -1) {
				out.write(this.header);
			}
			out.write(this.content);
			out.flush();
		} // end try
		catch (IOException ex) {

		}

	}

}